/**
 * 
 */
package com.es.disped.web.controller.rolepermission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.rolepermission.RolePermissionService;
import com.es.disped.common.model.MsgModel;
import com.es.disped.core.annotation.LogInject;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.model.PermissionNode;
import com.es.disped.dao.model.RolePermissionRel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author Anson<br>
 *
 * Copyright by EasyShare 2019<br>
 *
 * All right reserved<br>
 *
 * Created on 上午10:59:17<br>
 *
 * 名称：PermissionForRoleController.java<br>
 *
 * 描述：角色赋予权限<br>
 */
@Api(value="角色赋予权限")
@Controller
@RequestMapping("/manage/permission/role")
public class RolePermissionController extends BaseController{
	
	private static final String NAMESPACE="com.es.disped.dao.mapper.permission.PermissionCustomMapper";
	
	@LogInject
	Logger log;
	
	@Autowired
	RolePermissionService rolePermissionService;
	
	@ApiOperation(value="保存角色权限引用",httpMethod="POST",response=MsgModel.class,notes="为角色新增权限")
	@RequiresPermissions(value= {"admin:save","sys:save"},logical=Logical.OR)
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public @ResponseBody MsgModel save( @RequestBody @ApiParam(name="rolePermissionRel",value="角色权限引用关系对象",required=true) RolePermissionRel rolePermissionRel)
	{
		int count=0;
		if(Optional.of(rolePermissionRel)
				.filter(roleid->rolePermissionRel.getRoleId()!=null)
				.filter(pid->rolePermissionRel.getPermissionId()!=null)
				.isPresent())
		{
			rolePermissionRel.setRelId(getUUID());
			count=rolePermissionService.insert(rolePermissionRel);
		}
		log.debug(count==1?HttpStatus.OK.value()+"-为角色新增权限成功"
				:HttpStatus.EXPECTATION_FAILED.value()+"-为角色新增权限失败");
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"为角色新增权限成功":"为角色新增权限失败", rolePermissionRel);
	}
	
	@ApiOperation(value="更新角色权限引用",httpMethod="POST",response=MsgModel.class,notes="为角色更新权限")
	@RequiresPermissions(value= {"admin:update","sys:update"},logical=Logical.OR)
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public @ResponseBody MsgModel update( @RequestBody @ApiParam(name="rolePermissionRel",value="角色权限引用关系对象",required=true) RolePermissionRel rolePermissionRel)
	{
		int count=0;
		if(Optional.of(rolePermissionRel)
				.filter(relid->rolePermissionRel.getRelId()!=null)
				.isPresent())
		{
			count=rolePermissionService.updateByPrimaryKeySelective(rolePermissionRel);
		}
		log.debug(count==1?HttpStatus.OK.value()+"-为角色更新权限成功"
				:HttpStatus.EXPECTATION_FAILED.value()+"-为角色更新权限失败");
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"为角色更新权限成功":"为角色更新权限失败", rolePermissionRel);
	}
	
	@ApiOperation(value="回收角色权限引用",httpMethod="POST",response=MsgModel.class,notes="回收角色权限")
	@RequiresPermissions(value= {"admin:delete","sys:delete"},logical=Logical.OR)
	@RequestMapping(value="/recycle",method=RequestMethod.POST)
	public @ResponseBody MsgModel recycle( @RequestBody @ApiParam(name="rolePermissionRel",value="角色权限引用关系对象",required=true,example="relId=XXXX") RolePermissionRel rolePermissionRel)
	{
		int count=0;
		String relId=rolePermissionRel.getRelId();
		if(!this.isNull(relId))
		{
			count=rolePermissionService.deleteByPrimaryKey(relId);
		}
		log.debug(count==1?HttpStatus.OK.value()+"-回收角色权限成功"
				:HttpStatus.EXPECTATION_FAILED.value()+"-回收角色权限失败");
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"回收角色权限成功":"回收角色权限失败");
	}
	
	@ApiOperation(value="获取 checkbox 形式的 tree 结构（为角色管理提供支持）",response=MsgModel.class,httpMethod="POST",
			notes="根据角色ID和权限父类ID获取checked类型Tree列表-管理端")
//	@ApiImplicitParams({
//		@ApiImplicitParam(name="roleId",value="角色ID",required=true),
//		@ApiImplicitParam(name="permissionId",value="当前检索的角色类型的权限节点ID，若默认为空则从根节点开始",required=false)
//	})
	@RequiresPermissions(value= {"admin:select","sys:select"},logical=Logical.OR)
	@RequestMapping(value="/permissionCheckedTree",method=RequestMethod.POST)
	public @ResponseBody MsgModel getPermissionCheckedTree(@RequestBody @ApiParam(name="paramMap",value="当前检索的角色类型的权限节点ID，若默认为空则从根节点开始",required=false) Map<String, Object> paramMap)
	{
		if (!paramMap.containsKey("permissionId")) {
			paramMap.put("permissionId", "00000000000000000000000000000000");
        }
		
		List<PermissionNode> nodeList=new ArrayList<>();
		List<PermissionNode> rootList=this.getService().selectList(NAMESPACE+".getPermissionCheckedNode", paramMap);
		for(PermissionNode permissionNode:rootList)
		{
			permissionNode.setChildren(getPermissionCheckedNode(paramMap.get("roleId").toString(), permissionNode.getId()));
			nodeList.add(permissionNode);
		}
        return new MsgModel(nodeList.size()>0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
        		nodeList.size()>0?"":"列表加载失败", nodeList.size()>0?nodeList:"");
	}
	
	
	/**
	 * 获取 checkbox 形式的 tree 结构（为角色管理提供支持）
	 * @param roleId
	 * 		{@link String} roleId 角色ID
	 * @param pid
	 * 		{@link String} pid	权限父类ID
	 * @return
	 * 		List<PermissionNode> 权限节点列表集合
	 */
	private List<PermissionNode> getPermissionCheckedNode(String roleId, String pid) {
		Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("roleId", roleId);
        paramMap.put("permissionId", pid);
        List<PermissionNode> permissionList=this.getService().selectList(NAMESPACE+".getPermissionCheckedNode", paramMap);
        return permissionList;
	}
}
